package org.grapes.wine.api.server.method.impl.factory;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.grapes.wine.api.method.EWineMethod;
import org.grapes.wine.api.server.exception.MethodErrorCode;
import org.grapes.wine.api.server.exception.MethodException;
import org.grapes.wine.api.server.method.command.MethodCommand;
import org.grapes.wine.api.server.method.impl.MethodList;

public class MethodCommandFactory {
	static Logger logger = Logger.getLogger(MethodCommandFactory.class);
	
	public static MethodCommand newInstance(HttpServletRequest request) throws MethodException {	
		MethodCommand methodCommand = null;
		
		// method checking
		String method = request.getParameter("method");
		logger.info("method: " + method);
		Iterator it = EWineMethod.postAuthMethods().iterator();
		boolean found = false;
		while (it.hasNext()) {
			EWineMethod wineMethod = (EWineMethod) it.next();
			methodCommand = MethodList.getMethod(wineMethod);
			String methodCommandName = methodCommand.getMethodName().methodName();
			logger.info("methodCommandName: " + methodCommandName);
			
			if (method == null) {
				break;
			} else if (methodCommandName.equals(method)) {
				logger.info("found!");
				found = true;
				break;
			}
		}
		if (!found) {
			throw new MethodException(MethodErrorCode.METHOD_NOT_FOUND);
		}
		
		// parameter checking
		List param = methodCommand.getParam();
		Iterator paramIt = param.iterator();
		while (paramIt.hasNext()) {
			String str = paramIt.next().toString();
			String str2 = request.getParameter(str);
			if (str2 == null || (str2 != null && str2.length() == 0)) {
				throw new MethodException(MethodErrorCode.PARAMETER_NOT_MATCH);
			}
		}
		
		return methodCommand;
	}
}
